package net.gagnat.android.trackit.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.gagnat.android.trackit.db.DatabaseHelper;
import net.gagnat.android.trackit.domain.LogTag;
import net.gagnat.android.trackit.util.TrackItConstants.LogTagColumns;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;

class LogTagDbManager extends AbstractDbManager {

	private static final String[] PROJECTION = new String[] { LogTagColumns._ID, // 0
			LogTagColumns.NAME // 1
	};

	private static HashMap<String, String> sLogTagsProjectionMap;

	public LogTagDbManager(Context context) {
		super(context);
	}

	public List<LogTag> list() {
		ArrayList<LogTag> logTags = new ArrayList<LogTag>();

		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(DatabaseHelper.LOG_TAG_TABLE_NAME);
		qb.setProjectionMap(sLogTagsProjectionMap);

		Cursor cursor = qb.query(db, PROJECTION, null, null, null, null, LogTagColumns.DEFAULT_SORT_ORDER);
		if (cursor.moveToFirst()) {
			LogTag tag = null;
			do {
				tag = new LogTag();
				tag.setId(getLong(cursor, LogTagColumns._ID));
				tag.setName(getString(cursor, LogTagColumns.NAME));
				logTags.add(tag);
			} while (cursor.moveToNext());
		}

		return logTags;
	}

	public Long save(LogTag newTag) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(LogTagColumns.NAME, newTag.getName().trim());
		return db.insert(DatabaseHelper.LOG_TAG_TABLE_NAME, LogTagColumns.NAME, values);
	}

	static {
		sLogTagsProjectionMap = new HashMap<String, String>();
		sLogTagsProjectionMap.put(LogTagColumns._ID, LogTagColumns._ID);
		sLogTagsProjectionMap.put(LogTagColumns.NAME, LogTagColumns.NAME);
	}

}
